<template>
  <div class="list-course-build">
    <div class="course-list">
      <div class="course-item-add" @click="addCourse()">
        <el-icon :size="24" color="#457AFF"><CirclePlus /></el-icon>
        <span>创建课程</span>
      </div>
      <div
        class="course-item"
        v-for="(item, index) in courseBuildList"
        :key="index"
        @click="enterDetails(item)"
      >
        <div class="course-item-img"><img :src="item.iconPath" alt="" /></div>
        <div class="course-item-name">{{ item.name }}</div>
        <div class="foot-btns">
          <div class="edit-btn" @click.stop="editCourse(item)">
            <el-icon :size="12" color="#457AFF"><Edit /></el-icon>修改课程
          </div>
          <div class="del-btn" @click.stop="deleteCourse(item)">
            <el-icon :size="12" color="#457AFF"><Delete /></el-icon>删除
          </div>
        </div>
      </div>
    </div>

    <!-- 添加课程 -->
    <el-dialog v-model="addOrEditDialogVisible" width="33%">
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="课程名称：" prop="name">
          <el-input
            v-model="form.name"
            maxlength="20"
            show-word-limit
            placeholder="请输入课程名称"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="课程图标：" prop="imageUrl">
          <div class="upload-box">
            <el-upload
              ref="upload"
              class="avatar-uploader"
              action="/tes/unauthorized/config?keyword=courseIcon"
              name="file"
              :show-file-list="false"
              :limit="1"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :on-error="handleAvatarError"
            >
              <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <span class="tips">尺寸 420*180px，JPG、PNG格式</span>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="saveCourse()" class="save-btn"> 保存 </el-button>
          <el-button @click="addOrEditDialogVisible = false" class="cancel-btn"
            >取消</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!-- 删除课程弹窗 -->
    <el-dialog v-model="delDialogVisible" width="25%" class="delDialog">
      <div class="del-content">{{ delContent }}</div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="delDialogVisible = false" class="cancel-btn"
            >取消</el-button
          >
          <el-button @click="confirmDel()" class="save-btn" color="#457aff">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roles: "",
      addOrEditDialogVisible: false,
      delContent: "",
      errorDealFlag: "",
      isEdit: false,
      form: {
        name: "",
        imageUrl: "",
      },
      iconName: "",
      iconId: "",
      hasReuploadIcon: false, // 用户是否重新上传了图标
      directionIds: "",
      courseId: "",
      courseBuildList: [],
      rules: {
        name: [
          { required: true, message: "请输入课程名称", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
        imageUrl: [
          { required: true, message: "请上传课程图标", trigger: "change" },
        ],
      },
      delDialogVisible: false,
    };
  },
  created() {
    this.roles = JSON.parse(localStorage.getItem("userInfo")).roles[0];
    this.getDirectionIds();
    this.getCourseList();
  },
  methods: {
    // 获取专业方向
    getDirectionIds() {
      this.$axios
        .get(`/tes/direction/ztree?ownAuthorityFlag=true`)
        .then((res) => {
          if (res.code == 200) {
            this.directionIds = res.data[0].children[0].id;
          }
        });
    },

    // 获取课程列表
    getCourseList() {
      let url = "/tes/course/creation";
      if (this.roles == "internet_admin") {
        url = "/tes/course/creation?directionld=0";
      }
      this.$axios.get(url).then((res) => {
        if (res.code == 200) {
          this.courseBuildList = res.data;
        }
      });
    },

    // 进入详情
    enterDetails(item) {
      localStorage.setItem("courseId", item.id);
      localStorage.setItem("courseName", item.name);
      this.$router.push(`/aiTeaching/courseBuild/makeZhinengshibie`);
    },

    // 删除课程
    deleteCourse(item) {
      this.courseId = item.id;
      this.$confirm("您确定删除此课程吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$axios.delete(`/tes/course/${this.courseId}`).then((res) => {
          if (res.code == 200) {
            this.$message.success(res.message);
          } else if (res.code == 501) {
            // this.$message.error(res.message);
            this.delDialogVisible = true;
            this.delContent = res.message;
            return;
          } else {
            this.$message.error(res.msg);
          }
          this.getCourseList();
        });
      });
    },

    // 弹窗确认删除
    confirmDel() {
      this.$axios
        .delete(`/tes/course/${this.courseId}?errorDealFlag=true`)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success(res.message);
            this.delDialogVisible = false;
          } else {
            this.$message.error(res.msg);
          }
          this.getCourseList();
        });
    },

    // 添加课程
    addCourse() {
      this.isEdit = false;
      this.addOrEditDialogVisible = true;
      this.hasReuploadIcon = false;
      this.iconName = "";
      this.iconId = "";
      this.form = {
        name: "",
        imageUrl: "",
      };
      this.$nextTick(() => {
        this.$refs.upload.clearFiles();
      });
    },

    // 编辑课程
    editCourse(item) {
      this.courseId = item.id;
      this.isEdit = true;
      this.addOrEditDialogVisible = true;
      this.hasReuploadIcon = false;
      this.iconName = "";
      this.$axios.get(`/tes/course/${this.courseId}`).then((res) => {
        this.form.name = res.data.name;
        this.form.imageUrl = res.data.iconPath;
        this.iconId = res.data.icon;
      });
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传课程图标只能是JPG或PNG格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传课程图标大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    handleAvatarSuccess(res, file) {
      if (res.code == 200) {
        this.form.imageUrl = res.data.url;
        this.iconName = res.data.name;
        this.hasReuploadIcon = true;
        this.$message.success(res.message);

        this.$nextTick(() => {
          this.$refs.upload.clearFiles();
        });
      } else {
        this.$message.error(res.message);
        this.$nextTick(() => {
          this.$refs.upload.clearFiles();
        });
      }
    },
    handleAvatarError(err, file) {
      console.log(err, file);
      this.$message.error("上传失败，请重试!");
      // 错误时清除文件列表
      this.$nextTick(() => {
        this.$refs.upload.clearFiles();
      });
    },

    // 保存课程
    saveCourse() {
      // 添加
      if (!this.isEdit) {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.$axios
              .post("/tes/course", {
                name: this.form.name,
                iconName: this.iconName,
                imageLoadTypeStr: "章节加载",
                directionIds: [this.directionIds],
                typeName: "核心课程",
              })
              .then((res) => {
                if (res.code == 200) {
                  this.$message.success(res.message);
                  this.addOrEditDialogVisible = false;
                  this.getCourseList();
                } else {
                  this.$message.error(res.msg);
                }
              });
          }
        });
      } else {
        // 编辑
        this.$refs.form.validate((valid) => {
          if (valid) {
            const params = {
              name: this.form.name,
              imageLoadTypeStr: "章节加载",
              directionIds: [this.directionIds],
              typeName: "核心课程",
            };

            // 如果用户重新上传了图标，传iconName；否则传icon
            if (this.hasReuploadIcon) {
              params.iconName = this.iconName;
            } else {
              params.icon = this.iconId;
            }

            this.$axios
              .put(`/tes/course/${this.courseId}`, params)
              .then((res) => {
                if (res.code == 200) {
                  this.$message.success(res.message);
                  this.addOrEditDialogVisible = false;
                  this.getCourseList();
                } else {
                  this.$message.error(res.message);
                }
              });
          }
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.list-course-build {
  height: 100%;
  box-sizing: border-box;
  .course-list {
    display: flex;
    flex-wrap: wrap;
    gap: 30px;
    padding-bottom: 50px;
    .course-item {
      position: relative;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      gap: 28px;
      padding: 20px 20px 25px;
      width: calc(33% - 20px);
      height: 320px;
      background: #ffffff;
      box-shadow: 0px 0px 7px 0px rgba(70, 123, 235, 0.13);
      border-radius: 10px;
      cursor: pointer;
      box-sizing: border-box;
      &:hover {
        transform: scale(1.02);
        transition: transform 0.3s ease-in-out;
      }
      .course-item-img {
        width: 100%;
        height: 180px;
        border-radius: 10px;
        overflow: hidden;
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
      .course-item-name {
        font-weight: bold;
        font-size: 24px;
        color: #4a4966;
      }
      .foot-btns {
        position: absolute;
        bottom: 20px;
        right: 20px;
        display: flex;
        align-items: center;
        gap: 10px;
        .del-btn {
          display: flex;
          align-items: center;
          gap: 5px;
          font-size: 14px;
          color: #457aff;
          cursor: pointer;
        }
        .edit-btn {
          margin-right: 20px;
          display: flex;
          align-items: center;
          gap: 5px;
          font-size: 14px;
          color: #457aff;
          cursor: pointer;
        }
      }
    }
    .course-item-add {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      gap: 5px;
      width: calc(33% - 20px);
      height: 320px;
      background: #ffffff;
      box-shadow: 0px 0px 7px 0px rgba(70, 123, 235, 0.13);
      border-radius: 10px;
      border: 1px solid #ffffff;
      cursor: pointer;
      box-sizing: border-box;
      &:hover {
        transform: scale(1.02);
        transition: transform 0.3s ease-in-out;
      }
      span {
        font-size: 18px;
        color: #457aff;
      }
    }
    .el-dialog {
      .el-dialog__header {
        padding-bottom: 30px;
      }
    }
  }

  .el-dialog {
    .el-dialog__header {
      padding-bottom: 30px !important;
    }
    .dialog-footer {
      .save-btn {
        background-color: #155eef;
        color: #fff;
      }
    }
  }

  .delDialog {
    .del-content {
      padding: 20px;
    }
  }

  .upload-box {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    :deep(.avatar-uploader) {
      .avatar {
        width: 420px;
        height: 180px;
        object-fit: cover;
      }
    }

    :deep(.avatar-uploader .el-upload) {
      border: 1px dashed #dcdfe6;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      width: 420px;
      height: 180px;
    }

    :deep(.avatar-uploader .el-upload:hover) {
      border-color: #c0c4cc;
    }

    :deep(.avatar-uploader-icon) {
      font-size: 28px;
      color: #8c939d;
      width: 420px;
      height: 180px;
      text-align: center;
      line-height: 180px;
    }
    .tips {
      font-size: 14px;
      color: #a2a0b3;
    }
  }
}
</style>